//
//  YXDownloadManger.m
//  MockProject
//
//  Created by 周丽丽 on 16/8/26.
//  Copyright © 2016年 niuzhaowang. All rights reserved.
//

#import "YXDownloadManger.h"
#import "YXDownloader.h"
#import "DownloaderEntity.h"
#import "YXTaskListModel.h"
@interface YXDownloadManger ()
@property (nonatomic, assign) NSInteger downloadingCount;
@property (nonatomic, strong) NSMutableArray *saveDownloadersArr;
@end
@implementation YXDownloadManger
- (void)dealloc{
    [self.taskDownloadArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeObserver:self forKeyPath:@"state"];
    }];
}
+ (instancetype)sharedInstance
{
    static YXDownloadManger *_downloadManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _downloadManager = [[self alloc] init];
        _downloadManager.taskCompleteArr = [NSMutableArray array];
        _downloadManager.taskDownloadArr = [NSMutableArray array];
        _downloadManager.saveDownloadersArr = [NSMutableArray array];
    });
    return _downloadManager;
}
- (void)addDownloader:(YXDownloader *)downloader{
    [downloader addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    if (self.downloaderCompleteBlockForTaskListVC) {
        self.downloaderCompleteBlockForTaskListVC();
    }
    [self.taskDownloadArr addObject:downloader];
    downloader.state = TaskStatePrepare;
    [self judegWhetherToDownload:downloader];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //    NSLog(@"状态改变了---old:%@---new:%@",change[@"old"],change[@"new"]);
    NSNumber *newState = change[@"new"];
    NSNumber *oldState = change[@"old"];
    if (newState.intValue == TaskStatePause) {
        [self checkDownloaderState];
    }
    if (newState.intValue == TaskStateFialed) {
        [self checkDownloaderState];
    }
    if (newState.intValue == TaskStateResume) {
        [self judegWhetherToDownload:object];
    }
    if (newState.intValue == TaskStateComplete) {
        [self.taskDownloadArr removeObject:object];
        [self.taskCompleteArr insertObject:object atIndex:0];
        if (self.downloaderCompleteBlockForDownloadCompleteVC) {
            self.downloaderCompleteBlockForDownloadCompleteVC();
        }
        if (self.downloaderCompleteBlockForDownloadVC) {
            self.downloaderCompleteBlockForDownloadVC();
        }
        [self checkDownloaderState];
    }
    if (newState != oldState) {
        if (self.downloaderStateChangeBlock) {
            self.downloaderStateChangeBlock();
        }
    }
}
- (void)judegWhetherToDownload:(YXDownloader *)downloader{
    __block int count = 0;
    [self.taskDownloadArr enumerateObjectsUsingBlock:^(YXDownloader *  _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
        if (downloader.state == TaskStateDownloading) {
            count ++;
        }
    }];
    if (count < self.maxDownloadCountValue) {
        [downloader startDownload];
    }else{
        downloader.state = TaskStateWaiting;
    }
}
- (void)checkDownloaderState{
    __block int count = 0;
    [self.taskDownloadArr enumerateObjectsUsingBlock:^(YXDownloader *  _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
        if (downloader.state == TaskStateDownloading) {
            count ++;
            if (count > self.maxDownloadCountValue) {
                [self judegWhetherToDownload:downloader];
            }
        }
    }];
    if (count < self.maxDownloadCountValue && count != 0) {
        [self.taskDownloadArr enumerateObjectsUsingBlock:^(YXDownloader *  _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
            if (downloader.state == TaskStateWaiting) {
                [downloader startDownload];
                count++;
                if (count == self.maxDownloadCountValue) {
                    *stop = YES;
                }
            }
        }];
    }
}
- (void)removeDownloader:(YXDownloader *)downloader{
    [self.taskCompleteArr removeObject:downloader];
    [downloader removeObserver:self forKeyPath:@"state"];
}
- (void)removeAllCompleteDownloader{
    [self.taskCompleteArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeObserver:self forKeyPath:@"state"];
    }];
    [self.taskCompleteArr removeAllObjects];
}
- (void)setMaxDownloadCountValue:(NSInteger)maxDownloadCountValue{
    _maxDownloadCountValue = maxDownloadCountValue;
    [self checkDownloaderState];
}
#pragma mark - dataBase
- (void)saveAllDownloader{
    [DownloaderEntity MR_truncateAll];
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    NSLog(@"%@", NSHomeDirectory());
    [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
        [self.taskDownloadArr enumerateObjectsUsingBlock:^(YXDownloader * _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
            DownloaderEntity *entity = [DownloaderEntity MR_createEntityInContext:localContext];
            entity.content = [downloader toJSONString];
            entity.urlStr = downloader.urlStr;
            [self.saveDownloadersArr addObject:downloader];
        }];
        [self.taskCompleteArr enumerateObjectsUsingBlock:^(YXDownloader * _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
            DownloaderEntity *entity = [DownloaderEntity MR_createEntityInContext:localContext];
            entity.content = [downloader toJSONString];
            entity.urlStr = downloader.urlStr;
             [self.saveDownloadersArr addObject:downloader];
        }];
        if (self.saveDownloaderBlock) {
            self.saveDownloaderBlock();
        }
    }];
}
- (void)loadAllDownloader{
//    NSLog(@"%@",NSHomeDirectory());
    NSArray *arr = [DownloaderEntity MR_findAll];
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:arr.count];
    [arr enumerateObjectsUsingBlock:^(DownloaderEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        JSONModelError *error = nil;
        YXDownloader *downloader = [[YXDownloader alloc]initWithString:obj.content error:&error];
        [arrM addObject:downloader];
    }];
    [arrM enumerateObjectsUsingBlock:^(YXDownloader *_Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
        if (downloader.state == TaskStateComplete) {
            [self.taskCompleteArr addObject:downloader];
            [downloader addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        }else if (downloader.state == TaskStateNotStart){
        }else {
            [self.taskDownloadArr addObject:downloader];
            if (downloader.state == TaskStateDownloading || downloader.state == TaskStateWaiting) {
                downloader.state = TaskStatePause;
            }
            [downloader addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        }
    }];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.maxDownloadCountValue = [defaults integerForKey:kMaxDownloadCount];
    self.downloadingNetworkState = [defaults boolForKey:kNetworkSwitchState];
}
@end
